package com.example.recruitment.controller;

import com.example.recruitment.entity.User;
import com.example.recruitment.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public String login(@RequestParam String username, 
                       @RequestParam String password,
                       HttpSession session) {
        User user = userService.login(username, password);
        if (user != null) {
            session.setAttribute("user", user);
            
            // 获取原始请求URL
            String originalUrl = (String) session.getAttribute("originalUrl");
            if (originalUrl != null && !originalUrl.isEmpty()) {
                session.removeAttribute("originalUrl");
                return "redirect:" + originalUrl;
            }
            
            return "success";
        }
        return "用户名或密码错误";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }
} 